package com.hdoit.ares.web.wechat.handler;

import java.util.Map;

import javax.annotation.Resource;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

import org.springframework.stereotype.Component;

import com.tennetcn.common.logical.viewmodel.wechat.WechatOperateLogSearch;
import com.tennetcn.common.logical.wechat.model.WechatOperateLog;
import com.tennetcn.common.logical.wechat.service.IWechatOperateLogService;
import com.tennetcn.common.selfcommon.enums.wechat.WechatOperateType;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.web.cbase.wechat.handler.BaseTemplateSendJobFinishHandler;

@Component
public class TemplateSendJobFinishHandler extends BaseTemplateSendJobFinishHandler{
	private IWechatOperateLogService wechatOperateLogService;
	
	public IWechatOperateLogService getWechatOperateLogService() {
		return wechatOperateLogService;
	}
	@Resource
	public void setWechatOperateLogService(IWechatOperateLogService wechatOperateLogService) {
		this.wechatOperateLogService = wechatOperateLogService;
	}

	@Override
	protected WxMpXmlOutMessage beforeHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
		if(WxConsts.XML_MSG_EVENT.equals(wxMessage.getMsgType())){
			if(WxConsts.EVT_TEMPLATESENDJOBFINISH.equals(wxMessage.getEvent())){
				judgeResult(wxMessage,wxMpService);
			}
		}
		
		return null;
	}

	@Override
	protected WxMpXmlOutMessage afterHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
		return null;
	}

	//系统失败的时候会提示failed: system failed
	private void judgeResult(WxMpXmlMessage wxMessage,WxMpService wxMpService){
		if(wxMessage.getStatus().indexOf("failed")>=0&&wxMessage.getStatus().indexOf("system")>=0){
			String openId=wxMessage.getFromUser();
			String msgId=wxMessage.getMsgId().toString();
			
			WechatOperateLogSearch search=new WechatOperateLogSearch();
			
			search.setOperateResult(msgId);
			search.setOpenId(openId);
			search.setOperateType(WechatOperateType.sendTemplateMessage);
			
			WechatOperateLog wechatOperateLog=wechatOperateLogService.queryModel(search);
			String contextData=wechatOperateLog.getContextData();
			
			try{
				WxMpTemplateMessage templateMessage=JsonUtils.readValue(contextData, WxMpTemplateMessage.class);
				if(templateMessage!=null){
					wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
				}
			}catch(Exception ex){
			}
			
		}
	}
}
